package main

import (
	"fmt"
	"math/rand"
	"time"
)

func generator() chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond)
			out <- i
			i++
		}
	}()
	return out
}

func worker(id int, c chan int) {
	for n := range c {
		time.Sleep(time.Second)
		fmt.Printf("worker %d received %d \n", id, n)
	}
}

func createWorker(id int) chan<- int {
	c := make(chan int)
	go worker(id, c)
	return c
}

func main() {
	var c1, c2 = generator(), generator()

	var worker = createWorker(0)

	var values []int
	//设置，程序想要运行多久。记得在select里接一下
	tm := time.After(10 * time.Second)

	//设置一个定时器,每隔一段时间送一个值
	tick := time.Tick(time.Second)

	for {
		var activeWorker chan<- int //nil
		var activeValue int

		if len(values) > 0 {
			activeWorker = worker //有值的时候再初始化
			activeValue = values[0]
		}

		select {
		case n := <-c1:
			values = append(values, n)
		case n := <-c2:
			values = append(values, n)
		case activeWorker <- activeValue:
			values = values[1:]
		//数据生成太慢。超过800毫秒，还没有生成数据
		case <-time.After(800 * time.Millisecond):
			fmt.Println("timeout")
		//定时器。
		case <-tick:
			fmt.Println("queue len = ", len(values))
		//总共玩10秒
		case <-tm:
			fmt.Println("Bye!")
			return

		}
	}

}
